package com.panda.pandawash.util;

/**
 * Created by ubuntu on 17-3-24.
 */

import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Environment;
import android.util.Log;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

public class DownloadUtil {
    private int totalSize;
    private int progress;
    private File downFile = null;

    public DownloadUtil() {
    }

    public File downloadFile(String downUrl) {
        if(Environment.getExternalStorageState().equals("mounted")) {
            Log.d("url", "download - " + downUrl);

            try {
                URL e = new URL(downUrl);
                HttpURLConnection conn = (HttpURLConnection)e.openConnection();
                conn.setConnectTimeout(5000);
                this.totalSize = conn.getContentLength();
                if(this.totalSize <= 0) {
                    return null;
                }

                this.progress = 0;
                InputStream is = conn.getInputStream();
                String filename = downUrl.substring(downUrl.lastIndexOf("/") + 1);
                Log.d("url", "filename - " + filename);
                this.downFile = new File(Environment.getExternalStorageDirectory(), filename);
                FileOutputStream fos = new FileOutputStream(this.downFile);
                BufferedInputStream bis = new BufferedInputStream(is);

                int len;
                for(byte[] buffer = new byte[1024]; (len = bis.read(buffer)) != -1; this.progress += len) {
                    fos.write(buffer, 0, len);
                }

                fos.flush();
                fos.close();
                bis.close();
                is.close();
                conn.disconnect();
            } catch (MalformedURLException var10) {
                var10.printStackTrace();
                return null;
            } catch (IOException var11) {
                var11.printStackTrace();
                return null;
            }
        }

        return this.downFile;
    }

    public void installApk(Context mContext, File apkFile) {
        if(apkFile.exists()) {
            Intent i = new Intent("android.intent.action.VIEW");
            i.setDataAndType(Uri.parse("file://" + apkFile.toString()), "application/vnd.android.package-archive");
            i.addFlags(268435456);
            mContext.startActivity(i);
        }
    }

    public void setOnDownloadListener(IOnDownloadListener listener) {
        listener.updateNotification(this.progress, this.totalSize, this.downFile);
    }

    public interface IOnDownloadListener {
        void updateNotification(int var1, int var2, File var3);
    }
}
